import { message, Modal, Table } from 'antd';
import { TableRowSelection } from 'antd/es/table/interface';
import { useEffect, useState } from 'react';

import departmentService from '@/api/services/security/departmentService';
import { DepartmentType } from '@/pages/management/system/department/modal';
import { hasPermission } from '@/utils/permission';

import handleDepartmentData from '../department/handleDepartmentData';

import { ModalProps, UserInfo } from '#/entity';

export function UserDepartmentModal({ show, onOk, onCancel, formValue }: ModalProps<UserInfo>) {
  const [departments, setDepartments] = useState<DepartmentType[]>();
  useEffect(() => {
    // 获取所有的	部门
    if (hasPermission('DEPARTMENT:DEPARTMENT:READ')) {
      departmentService.getDepartmentsList({}).then((res) => {
        handleDepartmentData(res);
        setDepartments(res);
      });
    }
  }, []);
  useEffect(() => {
    // 初始化选中的	部门
    if (formValue.meta.DEPARTMENT) {
      setSelectedRowKeys(
        formValue.meta.DEPARTMENT.map((item: { id: number }) => {
          return item.id;
        }),
      );
    }
  }, [formValue]);
  const columns = [
    {
      title: '部门名称',
      dataIndex: 'name',
      key: 'name',
    },
  ];
  // 选中的部门
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };
  const rowSelection: TableRowSelection<DepartmentType> = {
    hideSelectAll: true,
    selectedRowKeys,
    onChange: onSelectChange,
    onSelect: (record: DepartmentType, selected: boolean) => {
      if (selected) {
        departmentService
          .departmentsUsers({
            departmentId: record.id,
            userId: formValue.id,
            operator: 'ADD',
          })
          .then((_) => {
            message.success(`为用户 ${formValue.name || ''} 添加部门 ${record.name} 成功`);
          });
      } else {
        departmentService
          .departmentsUsers({
            departmentId: record.id,
            userId: formValue.id,
            operator: 'REMOVE',
          })
          .then((_) => {
            message.success(`为用户 ${formValue.name || ''} 删除部门 ${record.name} 成功`);
          });
      }
    },
  };
  return (
    <Modal
      okText="确定"
      title={`为用户 ${formValue.name || ''} 添加部门`}
      open={show}
      onOk={onOk}
      onCancel={onCancel} // 隐藏取消按钮,但是保留取消功能
      cancelButtonProps={{ style: { display: 'none' } }}
      maskClosable
      keyboard
    >
      <Table
        rowKey="id"
        rowSelection={rowSelection}
        dataSource={departments}
        columns={columns}
        expandable={{
          // childrenColumnName: 'departementList',
          expandRowByClick: true,
        }}
        size="small"
      />
    </Modal>
  );
}
